package com.park.oss.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.beetl.sql.core.Params;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.park.oss.model.Place;
import com.park.oss.model.PlaceRent;
import com.park.oss.service.RentService;
import com.park.oss.util.ParkUtil;

/**
 * 展示了如何用sql和sqlTemplate直接操作。 不推荐使用，不容易维护，但比用sql文件更便捷
 * @author lijiazhi
 *
 */
@Service
public class RentServiceImpl implements RentService {
	@Autowired
	SQLManager sqlManager ;
	/* 查询n天以内的出租情况
	 */
	@Override
	public List<PlaceRent> query(Integer parkId,Integer userId,Integer day) {
		 String today = ParkUtil.today();
		 String target = ParkUtil.getDay(day);
		 //找到俩个日期范围内
		 String sql = "select * from place_rent where owner_id=? and park_id=?  and (day>=? and day<=?)";
		 Object[] paras = new Object[]{userId,parkId,today,target};
		 List<PlaceRent>  ret = sqlManager.execute(new SQLReady(sql,paras),PlaceRent.class);
		 List<PlaceRent>  all = new ArrayList<PlaceRent>(day);
		 for(int i=0;i<day;i++){
			 String strDay = ParkUtil.getDay(i);
			 PlaceRent  rent = hasRent(ret,strDay);
			 if(rent==null){
				 rent = new PlaceRent();
				 rent.setParkId(parkId);
				 rent.setOwnerId(userId);
				 rent.setDay(strDay);
				 rent.setStatus(-1);
				 all.add(rent);
			 }else{
				 all.add(rent);
			 }
		 }
		 
		 
		 return all;
	}
	
	private PlaceRent hasRent(List<PlaceRent> result, String strDay){
		
		for(PlaceRent rent: result){
			if(rent.getDay().equals(strDay)){
				return rent;
			}
		}
		return null ;
	}

	@Override
	public void updateRent(Integer rentId,Integer parkId, Integer userId, String day, Integer status) {
		
		String sqlTemplate = "select * from place where park_id=#parkId# and user_id=#userId#";
		//需要一个map参数
		List<Place> list = sqlManager.execute(sqlTemplate, Place.class,Params.ins().add("parkId", parkId).add("userId", userId).map());
		if(list.size()==0) throw new RuntimeException();
		Place place = list.get(0);
		
		if(status==-1){
			if(rentId==null){
				//增加一条
				PlaceRent rent = new PlaceRent();
				rent.setDay(day);
				rent.setEnd(null);
				rent.setOwnerId(userId);
				rent.setParkId(parkId);
				rent.setPlaceId(place.getId());
				rent.setRentType(1); //default
				rent.setStart(null);
				rent.setStatus(0); //avaiable
				rent.setUserId(null);
				sqlManager.insert(rent);
			}else{
				PlaceRent rent = sqlManager.unique(PlaceRent.class, rentId);
				rent.setStatus(0);
				sqlManager.updateById(rent);
			}
			
		}else{
			PlaceRent rent = sqlManager.unique(PlaceRent.class, rentId);
			rent.setStatus(-1);
			sqlManager.updateById(rent);
			
			
		}
		
	} 

}
